import storage from '@/utils/storage.js'
import httpApi from '@/network/api'

const StorgeKey = {
	submitType: 'submit_submitType',
}

// 提交订单store
export default {
	state: {
		// 下单类型
		submitType: storage.get(StorgeKey.submitType, '1'), // '1'为购物车下单，'2'为直接购买
	},
	mutations: {
		SET_submitType(state, type) {
			state.submitType = type
			storage.set(StorgeKey.submitType, type)
		}
	},
	actions: {
		// 改变商品数量
		ac_submit_goodsChange({
			state,
			dispatch,
			commit
		}, {
			item,
			num
		}) {
			if (state.submitType === '1') {
				dispatch('ac_editCartCount', {
					id: item.id,
					num
				})
			} else if (state.submitType === '2') {
				commit('SET_goodsCount', num)
			}
		},
		// 提交订单接口
		ac_submit_submitOrder({
			state,
			rootGetters
		}, {
			address_id,
			mark
		}) {
			let prom = null
			let params = {
				address_id,
				mark,
				total_price: rootGetters.submitAllGoodsPrice,
				// #ifdef APP-PLUS
				client_type: 'Wechat' //因为要跳转到微信小程序支付，所以填Wechat//APP
				// #endif
				// #ifdef MP-WEIXIN
				client_type: 'Wechat'
				// #endif
			}
			if (state.submitType === '1') {
				params.cart_ids = rootGetters.submitGoodsNumList.map(v => v.id).toString()
				prom = httpApi.api.submit_shop_cartBuy(params)
			} else if (state.submitType === '2') {
				params.id = rootGetters.submitGoodsNumList[0].goods.id,
					params.num = rootGetters.submitGoodsNumList[0].num,
					prom = httpApi.api.submit_shop_buy(params)
			}
			return prom.then(res => {
				console.log('订单ID：', res);
				return res
			})
		}
	},
	getters: {
		submitSubmitType: state => state.submitType,
		// 提交的商品及数量信息
		submitGoodsNumList: (state, rootGetters) => {
			if (state.submitType === '1') {
				return rootGetters.checkCartList
			} else if (state.submitType === '2') {
				return [{
					goods: rootGetters.directPurchaseGoodsItem,
					num: rootGetters.directPurchaseGoodsCount
				}]
			} else {
				return []
			}
		},
		// 提交总商品数量
		submitAllGoodsCount(state, rootGetters) {
			return rootGetters.submitGoodsNumList?.reduce((p, c) => p + c.num, 0) || 0
		},
		// 提交总商品金额
		submitAllGoodsPrice(state, rootGetters) {
			return rootGetters.submitGoodsNumList?.reduce((p, c) => (p + c.num * c.goods.price).toFixed(2), 0) || 0
		}
	}
}